// 引入EmailJS库，用于发送表单邮件
import emailjs from "@emailjs/browser";

// 引入React Three Fiber库中的Canvas组件以在React中渲染Three.js场景
import { Canvas } from "@react-three/fiber";

// 引入React Hook API
import { Suspense, useRef, useState } from "react";

// 引入预加载的3D模型（此处为Fox模型）
import { Fox } from "../models";

// 引入自定义的useAlert钩子函数，用于处理提示信息
import useAlert from "../hooks/useAlert";

// 引入自定义组件：Alert（提示框）和Loader（加载动画）
import { Alert, Loader } from "../components";

// 定义Contact组件，用于显示联系表单和3D模型动画
const Contact = () => {
  // 创建一个React Ref对象，用于获取表单DOM元素
  const formRef = useRef();
  // 初始化表单状态，存储用户输入的信息
  const [form, setForm] = useState({ name: "", email: "", message: "" });
  // 使用useAlert钩子获取和控制提示信息的显示
  const { alert, showAlert, hideAlert } = useAlert();
  // 控制表单提交时的加载状态
  const [loading, setLoading] = useState(false);
  // 控制3D模型动画的状态
  const [currentAnimation, setCurrentAnimation] = useState("idle");

  // 处理表单字段更改事件
  const handleChange = ({ target: { name, value } }) => {
    setForm({ ...form, [name]: value });
  };

  // 当表单字段获得焦点时，切换3D模型至行走动画
  const handleFocus = () => setCurrentAnimation("walk");
  // 当表单字段失去焦点时，切换3D模型回默认动画
  const handleBlur = () => setCurrentAnimation("idle");

  // 处理表单提交事件
  const handleSubmit = (e) => {
    e.preventDefault();
    setLoading(true);
    setCurrentAnimation("hit");

    // 使用EmailJS发送邮件
    emailjs
      .send(
        import.meta.env.VITE_APP_EMAILJS_SERVICE_ID,
        import.meta.env.VITE_APP_EMAILJS_TEMPLATE_ID,
        {
          from_name: form.name,
          to_name: "xtcBear",
          from_email: form.email,
          to_email: "728611827@qq.com",
          message: form.message,
        },
        import.meta.env.VITE_APP_EMAILJS_PUBLIC_KEY
      )
      .then(
        () => {
          setLoading(false);
          // 提交成功后显示成功提示，并在3秒后重置表单和动画
          showAlert({
            show: true,
            text: "感谢你的留言 😃",
            type: "success",
          });

          setTimeout(() => {
            hideAlert(false);
            setCurrentAnimation("idle");
            setForm({
              name: "",
              email: "",
              message: "",
            });
          }, 3000);
        },
        (error) => {
          setLoading(false);
          // 记录错误日志，并显示错误提示
          console.error(error);
          setCurrentAnimation("idle");

          showAlert({
            show: true,
            text: "I didn't receive your message 😢",
            type: "danger",
          });
        }
      );
  };
  return (
    <section className='relative flex lg:flex-row flex-col max-container'>
      {alert.show && <Alert {...alert} />}

      <div className='flex-1 min-w-[50%] flex flex-col'>
        <h1 className='head-text'>联系我</h1>

        <form
          ref={formRef}
          onSubmit={handleSubmit}
          className='w-full flex flex-col gap-7 mt-14'
        >
          <label className='text-black-500 font-semibold'>
            姓名
            <input
              type='text'
              name='name'
              className='input'
              placeholder='xtc'
              required
              value={form.name}
              onChange={handleChange}
              onFocus={handleFocus}
              onBlur={handleBlur}
            />
          </label>
          <label className='text-black-500 font-semibold'>
            电子邮件
            <input
              type='email'
              name='email'
              className='input'
              placeholder='xtc2016xct@emailjs'
              required
              value={form.email}
              onChange={handleChange}
              onFocus={handleFocus}
              onBlur={handleBlur}
            />
          </label>
          <label className='text-black-500 font-semibold'>
            你的留言
            <textarea
              name='message'
              rows='4'
              className='textarea'
              placeholder='Write your thoughts here...'
              value={form.message}
              onChange={handleChange}
              onFocus={handleFocus}
              onBlur={handleBlur}
            />
          </label>

          <button
            type='submit'
            disabled={loading}
            className='btn'
            onFocus={handleFocus}
            onBlur={handleBlur}
          >
            {loading ? "Sending..." : "Submit"}
          </button>
        </form>
      </div>

      <div className='lg:w-1/2 w-full lg:h-auto md:h-[550px] h-[350px]'>
        <Canvas
          camera={{
            position: [0, 0, 5],
            fov: 75,
            near: 0.1,
            far: 1000,
          }}
        >
          <directionalLight position={[0, 0, 1]} intensity={2.5} />
          <ambientLight intensity={1} />
          <pointLight position={[5, 10, 0]} intensity={2} />
          <spotLight
            position={[10, 10, 10]}
            angle={0.15}
            penumbra={1}
            intensity={2}
          />

          <Suspense fallback={<Loader />}>
            <Fox
              currentAnimation={currentAnimation}
              position={[0.5, 0.35, 0]}
              rotation={[12.629, -0.6, 0]}
              scale={[0.5, 0.5, 0.5]}
            />
          </Suspense>
        </Canvas>
      </div>
    </section>
  );
};

export default Contact;
